package gameserver.model.account;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Account implements Iterable<PlayerAccountData>
{
	private final int id;

	private String name;

	private AccountTime accountTime;

	private Map<Integer, PlayerAccountData> players = new HashMap<Integer, PlayerAccountData>();

	public Account(int id)
	{
		this.id = id;
	}

	public int getId()
	{
		return id;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public AccountTime getAccountTime()
	{
		return accountTime;
	}

	public void setAccountTime(AccountTime accountTime)
	{
		this.accountTime = accountTime;
	}

	@Override
	public boolean equals(Object o)
	{
		if (this == o)
		{
			return true;
		}

		if (!(o instanceof Account))
		{
			return false;
		}

		Account account = (Account) o;

		return id == account.id;
	}

	@Override
	public int hashCode()
	{
		return id;
	}

	public PlayerAccountData getPlayerAccountData(int chaOid)
	{
		return players.get(chaOid);
	}

	public void addPlayerAccountData(PlayerAccountData accPlData)
	{
		players
				.put(accPlData.getPlayerCommonData().getPlayerObjId(),
						accPlData);
	}

	public int size()
	{
		return players.size();
	}

	public ArrayList<PlayerAccountData> getSortedAccountsList()
	{
		ArrayList<PlayerAccountData> list = new ArrayList<PlayerAccountData>();
		list.addAll(players.values());
		Collections.sort(list, new Comparator<PlayerAccountData>()
		{
			@Override
			public int compare(PlayerAccountData x, PlayerAccountData y)
			{
				Timestamp t1 = x.getPlayerCommonData().getLastOnline();
				Timestamp t2 = y.getPlayerCommonData().getLastOnline();
				if (t2 == null)
				{
					return 1;
				} else if (t1 == null)
				{
					return -1;
				}
				return y.getPlayerCommonData().getLastOnline().compareTo(
						x.getPlayerCommonData().getLastOnline());
			}
		});
		return list;
	}
	
	@Override
    public Iterator<PlayerAccountData> iterator() {
        return players.values().iterator();
    }
}
